<?php
    echo "<head>
        <title>Output</title>
        <link rel=\'stylesheet\' type=\'text/css\' href=\'../CSS/pages.css\'/>
        </head>
        <body>
        <table>";

    include 'dbconf.php';
    include 'dbopen.php';
    include 'functions.php';


	/*
	 * Get file locations from Misc/localization_files.txt
	 */

	$locFile = file("../Misc/localization_files.txt");
	foreach ($locFile as $locFileLine) {
    	if(substr($locFileLine,0,12) == "Rscript_path"){
    		$Rscript_path = trim(str_replace("=","",str_replace("Rscript_path","",$locFileLine))); 
    	}
	}


	if(file_exists("../Images/genes_vs_genes.png")){
    	unlink("../Images/genes_vs_genes.png");
	}
	if(file_exists("../TXT/raw_data.xls")){
    	unlink("../TXT/raw_data.xls");
	}


    $input_gene_sym1 = $_POST['input_gene_sym1'];
    $input_gene_sym1 = preg_split('/\r/', $input_gene_sym1);

    $input_gene_sym2 = $_POST['input_gene_sym2'];
    $input_gene_sym2 = preg_split('/\r/', $input_gene_sym2);

    $input_tissue = $_POST['bike_tissue'];

    // Remove any empty rows or trailing newlines
    $input_gene_sym1 = removeEmptyRows($input_gene_sym1);
    $input_gene_sym2 = removeEmptyRows($input_gene_sym2);
   
    // Check for bogus gene symbols
    checkGeneSyms($input_gene_sym1);
    checkGeneSyms($input_gene_sym2);
    
    $nbrOfInputGenes1 = sizeof($input_gene_sym1);
    $nbrOfInputGenes2 = sizeof($input_gene_sym2);

    
    
    $arrayOfExp1Values = array();
    $arrayOfExp2Values = array();
    $annotationArray = array();
    
    
    global $picnumber; $picnumber = 0;
    global $a;
    global $b;
    $a=0;
    while ($a < $nbrOfInputGenes1) {

        $genesym1_trim = trim($input_gene_sym1[$a]);
        $b=0;

        while ($b < $nbrOfInputGenes2) {

            $genesym2_trim = trim($input_gene_sym2[$b]);

            /*
             * First gene
             */

            $probe_id_res1 = mysql_query(getProbeIdFromGeneSymbol($genesym1_trim));

            while ($row1 = mysql_fetch_array($probe_id_res1)) {

                $ind_probe_id1 = $row1['probe_id'];
              
                global $exp1_temp;
                global $exp2_temp;
                global $ind_nbrs;

                /*
                $expression1_res = mysql_query(getExpressionLevel($ind_probe_id1));

                while ($row11 = mysql_fetch_array($expression1_res)) {
                    $exp1_temp = $exp1_temp . "\t" . $row11['exp_level'];

                }

                 */

                /*
                 * Second gene
                 */
                $probe_id_res2 = mysql_query(getProbeIdFromGeneSymbol($genesym2_trim));

                while ($row2 = mysql_fetch_array($probe_id_res2)) {

                    $ind_probe_id2 = $row2['probe_id'];

                    /*
                    $expression2_res = mysql_query(getExpressionLevel($ind_probe_id2));


                    
                    while ($row22 = mysql_fetch_array($expression2_res)) {                        
                        $exp2_temp = $exp2_temp . "\t" . $row22['exp_level'];
                    }

                     */

                    $exp_res = mysql_query(getGeneVsGeneJoin($ind_probe_id1, $ind_probe_id2, $input_tissue));

                    $exp1_temp = "";
                    $exp2_temp = "";
                    $ind_nbrs = "";
                    
                    while ($row3 = mysql_fetch_array($exp_res)) {
                        $exp1_temp = $exp1_temp . "\t" . $row3['exp1'];
                        $exp2_temp = $exp2_temp . "\t" . $row3['exp2'];
                        $ind_nbrs = $ind_nbrs . "\t" . $row3['ind_nbr'];
                    }

                    $exp_level_array1 = preg_split('/\t/', $exp1_temp, -1, PREG_SPLIT_NO_EMPTY);
                    $exp_level_array2 = preg_split('/\t/', $exp2_temp, -1, PREG_SPLIT_NO_EMPTY);
                    $ind_nbr_array = preg_split('/\t/', $ind_nbrs, -1, PREG_SPLIT_NO_EMPTY);


					$arrayOfExp1Values[$ind_probe_id1] = $exp_level_array1;
					$arrayOfExp2Values[$ind_probe_id2] = $exp_level_array2;

#                    /*
#                     * 1st expression file
#                     */
#
#                    $explvlFile1 = "../TXT/exp1_genevsgene.txt";
#                    $fh_explvlFile1 = fopen($explvlFile1, 'w');
#                    fwrite($fh_explvlFile1, "\t"."X".$ind_probe_id1."\r");
#
#                    $nbrOfIndividuals = count($ind_nbr_array);
#                    
#                    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
#                        fwrite($fh_explvlFile1, $ind_nbr_array[$counter]."\t");
#                        fwrite($fh_explvlFile1, $exp_level_array1[$counter]."\r");
#                    }
#                    fclose($fh_explvlFile1);
#
#                    /*
#                     * 2nd expression file
#                     */
#
#                    $explvlFile2 = "../TXT/exp2_genevsgene.txt";
#                    $fh_explvlFile2 = fopen($explvlFile2, 'w');
#                    fwrite($fh_explvlFile2, "\t"."X".$ind_probe_id2."\r");
#
#                    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
#                        fwrite($fh_explvlFile2, $ind_nbr_array[$counter]."\t");
#                        fwrite($fh_explvlFile2, $exp_level_array2[$counter]."\r");
#                    }
#                    fclose($fh_explvlFile2);


                    /*
                     * Start of annotation file creation, thats going to be sent to R.
                     */

                    /*
                     * For gene symbol 1:
                     */

                    $AnnotationQueryResult = mysql_query(getAnnotation($ind_probe_id1))
                            or die ("ERROR: could not send/execute query getAnnotation!".  mysql_error());

                    $temp1 = mysql_fetch_array($AnnotationQueryResult);
                    $temp1['gene_sym'];

                    $nbrRowsAnnotationQuery=mysql_numrows($AnnotationQueryResult);

                    $probe_id_temp = "";
                    $gene_sym_temp = "";
                    $gene_name_temp = "";

                    $k=0;
                    while ($k < $nbrRowsAnnotationQuery) {
                        $probe_id_temp = mysql_result($AnnotationQueryResult,$k,'probe_id');
                        $gene_sym_temp = mysql_result($AnnotationQueryResult,$k,'gene_sym');
                        $gene_name_temp = mysql_result($AnnotationQueryResult,$k,'gene_name');

                        $k++;
                    }

					$annotationArray[$probe_id_temp] = $gene_sym_temp."\t".$gene_name_temp;

#
#                    $annotation_file = "../TXT/annotation_genevsgene.txt";
#                    $fh_annotationfile = fopen($annotation_file, 'w');
#                    fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");
#                    fwrite($fh_annotationfile, $probe_id_temp . "\t" . $gene_sym_temp ."\t" . $gene_name_temp);
#                    fwrite($fh_annotationfile, "\r");
                    //fclose($fh_annotationfile);

                    /*
                     * For gene symbol 2:
                     */

                    $AnnotationQueryResult = mysql_query(getAnnotation($ind_probe_id2))
                            or die ("ERROR: could not send/execute query getAnnotation!".  mysql_error());

                    $temp1 = mysql_fetch_array($AnnotationQueryResult);
                    $temp1['gene_sym'];

                    $nbrRowsAnnotationQuery=mysql_numrows($AnnotationQueryResult);

                    $probe_id_temp = "";
                    $gene_sym_temp = "";
                    $gene_name_temp = "";

                    $k=0;
                    while ($k < $nbrRowsAnnotationQuery) {
                        $probe_id_temp = mysql_result($AnnotationQueryResult,$k,'probe_id');
                        $gene_sym_temp = mysql_result($AnnotationQueryResult,$k,'gene_sym');
                        $gene_name_temp = mysql_result($AnnotationQueryResult,$k,'gene_name');

                        $k++;
                    }
					
					$annotationArray[$probe_id_temp] = $gene_sym_temp."\t".$gene_name_temp;
					
//                    $annotation_file = "../TXT/annotation_genevsgene.txt";
//                    $fh_annotationfile = fopen($annotation_file, 'a');
#                    fwrite($fh_annotationfile, $probe_id_temp . "\t" . $gene_sym_temp ."\t" . $gene_name_temp);
#                    fwrite($fh_annotationfile, "\r");
#                    fclose($fh_annotationfile);
#
#
#
#					
#                    system("\"C:\Program Files\R\R-2.13.0\bin\Rscript.exe\" ../R/genes_vs_genes.R $picnumber");
#
#                    $nocache = rand();
#
#                    if ($picnumber % 4 == 0 && $picnumber != 0) {
#                        echo "</tr><tr><td><form method=\"post\" action=\"\"><input type=\"checkbox\" name=\"pic_id\" value=\"$picnumber\"></td>
#                                  <td>
#                                    <a href='../Images/genes_vs_genes$picnumber.png?$nocache'>
#                                        <img width=\"300\" height=\"300\" src='../Images/genes_vs_genes$picnumber.png?$nocache'>
#                                        </a>
#                                    </td>";
#                    }
#
#                    else {
#                        echo "<td><form method=\"post\" action=\"\"><input type=\"checkbox\" name=\"pic_id\" value=\"$picnumber\"></td>
#                                  <td>
#                                      <a href='../Images/genes_vs_genes$picnumber.png?$nocache'>
#                                        <img width=\"300\" height=\"300\" src='../Images/genes_vs_genes$picnumber.png?$nocache'>
#                                        </a>
#                                    </td>";
#                    }
#
#                    $picnumber++;

                }
            }

            $b++;
        }

        $a++;
    }
    
    /*
     * Tissue type file
     */

    $tissue_file = "../TXT/tissuetype_genevsgene.txt";
    $fh_tissuefile = fopen($tissue_file, 'w');
    fwrite($fh_tissuefile, $input_tissue."\r");
    fclose($fh_tissuefile);
    
    
  
     /*
     * 1st expression file
     */

    $explvlFile1 = "../TXT/exp1_genevsgene.txt";
    $fh_explvlFile1 = fopen($explvlFile1, 'w');
    
    $probesetsToPrint = array_keys($arrayOfExp1Values);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_explvlFile1, "\t"."X".$probeset);
    }
    fwrite($fh_explvlFile1, "\r");


    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_explvlFile1, $ind_nbr_array[$counter]);
        foreach ($probesetsToPrint as $probeset) {
        	fwrite($fh_explvlFile1, "\t".$arrayOfExp1Values[$probeset][$counter]);
        	
        }
        fwrite($fh_explvlFile1, "\r");
    }
    fclose($fh_explvlFile1);

    /*
     * 2nd expression file
     */

    $explvlFile2 = "../TXT/exp2_genevsgene.txt";
    $fh_explvlFile2 = fopen($explvlFile2, 'w');
    
    $probesetsToPrint = array_keys($arrayOfExp2Values);
    
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_explvlFile2, "\t"."X".$probeset);
    }
    fwrite($fh_explvlFile2, "\r");


    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_explvlFile2, $ind_nbr_array[$counter]);
      	foreach ($probesetsToPrint as $probeset) {
        	fwrite($fh_explvlFile2, "\t".$arrayOfExp2Values[$probeset][$counter]);
        }
        fwrite($fh_explvlFile2, "\r");
    }
    fclose($fh_explvlFile2);
    
    /*
     * annotation file
     */

	$annotation_file = "../TXT/annotation_genevsgene.txt";
    $fh_annotationfile = fopen($annotation_file, 'w');
    fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");

    $probesetsToPrint = array_keys($annotationArray);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_annotationfile, $probeset."\t".$annotationArray[$probeset]."\r");
    }


    
    
    system("$Rscript_path ../R/genes_vs_genes.R");



    
    $nocache = rand();
    echo "
    <td>
    <img src='../Images/genes_vs_genes.png?$nocache'>
    </td>";
                    
                    		
					
    
   echo "</table>
   <br>
   
   <a href='../PDF/genes_vs_genes.pdf?$nocache'>
   PDF-file with plots
   </a>
   <br>
   
   <a href='../TXT/raw_data.xls?$nocache'>
   Text file with raw data
   </a>
   
   
   </form>
   </body>
   </html>";
   
   include 'dbclose.php';
?>
